﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;

namespace FrontEndPlus.Módulos.Seguridad
{
    public class cls_Ftp_Remote_Download : cls_Remote_Download
    {
        public cls_Ftp_Remote_Download(string urlString, string descFilePath, string usuario, string password)
            : base(urlString, descFilePath, usuario, password)
        {

        }

        public override string DownloadFile()
        {
            FtpWebRequest reqFTP;

            string fileName = Path.GetFileName(this.UrlString);
            string descFilePathAndName = Path.Combine(this.DestDir, fileName);

            try
            {
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(this.UrlString);
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.KeepAlive = true;
                reqFTP.Credentials = new NetworkCredential(Usuario, Password);

                using (FileStream outputStream = new FileStream(descFilePathAndName, FileMode.OpenOrCreate))
                using (FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse())
                using (Stream ftpStream = response.GetResponseStream())
                {
                    int bufferSize = 2048;
                    int readCount;
                    byte[] buffer = new byte[bufferSize];
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                    while (readCount > 0)
                    {
                        outputStream.Write(buffer, 0, readCount);
                        readCount = ftpStream.Read(buffer, 0, bufferSize);
                    }
                }
                return "Descarga Correcta en el directorio";
            }
            catch (Exception ex)
            {
                return "Error en la Descarga... Verifique tener los permisos correspondientes en el directorio de descarga";
            }
        }

        public string verificaFTP()
        {
            try
            {
                FtpWebRequest dirFtp = ((FtpWebRequest)FtpWebRequest.Create(this.UrlString));
                NetworkCredential cr = new NetworkCredential(Usuario, Password);
                dirFtp.Credentials = cr;
                dirFtp.Method = "LIST";
                dirFtp.Method = WebRequestMethods.Ftp.ListDirectory;
                StreamReader reader = new StreamReader(dirFtp.GetResponse().GetResponseStream());
                return "Correcto";
            }
            catch (WebException e)
            {
                return e.Message;
            }
        }
    }
}